package com.example.cato_message_rabbitmq.message;
/*
  spring 对rabbitmq消息支持核心是RabbitTemplate，与Jms不同，RabbitTemplate按照Exchange和routing key发送消息
  void send（）发送原始消息
  void convertAndSend（）发送根据根据对象转换的消息
  void convertAndSend（MessagePostProcessor messagePostProcessor） 发送根据对象转换成的消息并且带有后期处理功能
 */

import com.example.cato_entity.entity.Order;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service

public class RabbitOrderMessagingService implements OrderMessagingService {

    private RabbitTemplate rabbit;

    @Autowired
    public RabbitOrderMessagingService(RabbitTemplate rabbit) {
        this.rabbit = rabbit;
    }

    @Override
    public void sendOrder(Order order) {
        rabbit.convertAndSend("tacocloud.order", order, new MessagePostProcessor() {

            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                MessageProperties props = message.getMessageProperties();
                props.setHeader("X_ORDER_SOURCE", "WEB");
                return message;
            }
        });
    }
     /*
     指定了routing key 和消息本身，所以会使用默认的exChange，默认的交换机名字是"",默认的routing Key也是"",可以通过配置文件来重写
      */
//    @Override
//    public void sendOrder(Order order) {
//        MessageConverter converter = rabbit.getMessageConverter();
//        MessageProperties props = new MessageProperties();
//        props.setHeader("X_ORDER_SOURCE","WEB");  //设置头信息
//        Message message = converter.toMessage(order,props);
//        rabbit.send("tacocloud.order",message);
//    }
}
